import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class Homework_UdpEchoClient {
    private DatagramSocket socket = new DatagramSocket();
    private String serverIp = "";
    private int serverPort = 0;
    public Homework_UdpEchoClient(String ip, int port) throws SocketException {
        //需要系统自动分配端口
        socket = new DatagramSocket();
        this.serverIp = ip;
        this.serverPort = port;
    }
    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);
        while(true){
            //1.发送请求
            System.out.println("-> ");
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(this.serverIp), this.serverPort);
            socket.send(requestPacket);
            //2.等待服务器响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096,
                    InetAddress.getByName(this.serverIp), this.serverPort);
            socket.receive(responsePacket);
            //3.打印响应信息
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        Homework_UdpEchoClient client = new Homework_UdpEchoClient("127.0.0.1", 9999);
        client.start();
    }
}
